<template>
	<view class="container">
		<view class="left-bottom-sign"></view>
		<!-- <view class="back-btn yticon icon-zuojiantou-up" @click="navBack"></view> -->
		<view class="right-top-sign"></view>
		<!-- 设置白色背景防止软键盘把下部绝对定位元素顶上来盖住输入框等 -->
		<view class="wrapper">
			<view class="left-top-sign">LOGIN</view>
			<view class="welcome">欢迎回来！</view>
			<!-- #ifdef MP-WEIXIN -->
			<!-- <button class="confirm-btn" open-type="getUserInfo" @getuserinfo="wxGetUserInfo" withCredentials="true">微信登录</button> -->
			<button class="confirm-btn" @click="openTishi()">手机号快捷登录</button>
			<!-- #endif -->
			<!-- #ifdef MP-ALIPAY -->
			<button class="confirm-btn" open-type="getAuthorize" @getAuthorize="onGetAuthorize" @error="onAuthError"
				scope='userInfo'>支付宝登录</button>
			<!-- #endif -->
			<!-- #ifdef MP-TOUTIAO -->
			<button v-if="!isLogin" class="confirm-btn" @click="ttGetUserInfo">抖音登录</button>
			<button v-if="isLogin" class="confirm-btn" open-type="getPhoneNumber"
				@getphonenumber="getPhoneNumber">手机号快捷登录</button>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<button class="confirm-btn" @click="wechatH5Login" :disabled="logining">授权登录</button>
			<!-- #endif -->
			
			<uni-popup ref="tishi" :mask-click="false" type="center">
				<view class="unipopup">
					<view class="successtxt">
						<text>温馨提示</text>
					</view>
					<view class="tishicontent">
						<text>为了给您提供更加优质的服务,我们需要获取您的手机号以便于及时联系您,我们承诺不会将您的手机号外泄或用于其他用途</text>
					</view>
					<view style="display: flex;margin-top: 80rpx;margin-left: 15rpx;">
						<view class="buttomopendoor1" @click="closeTishi()"><text>不同意授权</text></view>
						<view>
							<button class="buttomafrim" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">同意授权</button>
						</view>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState
	} from 'vuex';
	import Api from '@/common/api';
	import WXBizDataCrypt from '@/common/WXBizDataCrypt';
	import store from '@/store/index';
	export default {
		data() {
			return {
				loginType: '',
				logining: false,
				fromMemberId: null,
				sessionKey: '',
				isLogin: false,
				appId: '',
				openId: '',
				code:''
			};
		},
		onLoad() {},
		computed: {
			...mapState(['hasLogin', 'userInfo'])
		},
		methods: {
			...mapMutations(['login']),
			navBack() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			},
			openTishi(){
				let that = this;
				wx.login({
					success(res) {
						if (res.code) {
							//发起网络请求
							console.log(res.code)
							that.code = res.code
						} else {
							console.log('登录失败！' + res.errMsg)
						}
					}
				})
				this.$refs.tishi.open('center')
			},
			getPhoneNumber(e) {
				// let that = this;
				// wx.login({
				// 	success(res) {
				// 		if (res.code) {
				// 			//发起网络请求
				// 			that.getopenId(res.code,e);
				// 		} else {
				// 			console.log('登录失败！' + res.errMsg)
				// 		}
				// 	}
				// })
				this.getopenId(this.code,e)
			},
			async getopenId(code,e) {
				let that = this;
				console.log(11111111111111111111)
				let data = await Api.apiCall('get', 'member/getopenid', {
					code: code
				});
				that.sessionKey = data.session_key;
				that.openId = data.openid;
				if(data){
					wx.checkSession({
						success: function() {
							console.log(e)
							var ency = e.detail.encryptedData;
							var iv = e.detail.iv;
							var sessionk = data.session_key;
							if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
								console.log('拒绝授权')
					
							} else { //同意授权
							console.log('同意授权了')
								wx.request({
									method: "GET",
									url: Api.BASEURI + 'member/deciphering',
									data: {
										encrypdata: ency,
										ivdata: iv,
										sessionkey: sessionk,
										openid:data.openid
									},
									header: {
										'content-type': 'application/json' // 默认值
									},
									success: function(res){
										console.log(res.data.data)
										that.login(res.data.data);
										uni.switchTab({
											url: '/pages/meallist/selectRoom'
										});
									},
									fail: function(res) {
										console.log("解密失败~~~~~~~~~~~~~");
										console.log(res);
									}
								});
							}
					
						},
					
						fail: function() {
							console.log("session_key 已经失效，需要重新执行登录流程");
							that.wxlogin(); //重新登录
						}
					});
				}
			},
			closeTishi(){
				this.$refs.tishi.close()
			},
			getUserProfile() {
				let that = this;
				wx.login({
					success(res) {
						if (res.code) {
							//发起网络请求
							that.getopenId(res.code);
						} else {
							console.log('登录失败！' + res.errMsg)
						}
					}
				})
			},
			wxGetUserInfo: function(res) {
				if (!res.detail.iv) {
					uni.showToast({
						title: '您取消了授权,登录失败',
						icon: 'none'
					});
					return false;
				}
				const that = this;
				let currentStoreId = Api.STORE_ID;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						wx.request({
							url: Api.BASEURI + Api.index.appletLogin_by_weixin,
							data: {
								code: loginRes.code,
								userInfo: res.detail.rawData,
								cloudID: res.detail.cloudID,
								encrypted_data: res.detail.encryptedData,
								iv: res.detail.iv,
								source: 2,
								signature: res.detail.signature,
								storeId: currentStoreId
							},
							method: 'post',
							success: function(info) {
								console.log("登录返回信息" + info.data.data);
								that.login(info.data.data);
								let fid = uni.getStorageSync("fromMemberId");
								if (undefined != fid && null != fid && "" != fid) {
									that.fromMemberId = fid;
								}
								if (null != that.fromMemberId) {
									let logparams = {
										logs: "绑定会员关系" + info,
										fromMemberId: that.fromMemberId,
									};
									let result = Api.apiCall('get', Api.index.logs, logparams);
								}
								uni.switchTab({
									url: '/pages/index/index'
								});
							},
							fail: function(e) {
								console.log("微信登录失败.");
							}
						});
					}
				});
			},
			ttGetUserInfo:function(){
				console.log("抖音登录");
				let that = this;
				tt.login({
				  force: true,
				  success(res) {
				    console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
					// tt.getUserInfo({
					//   withCredentials: true,
					//   success(res) {
					//     console.log(`getUserInfo 调用成功 ${res.userInfo}`);
					//   },
					//   fail(res) {
					//     console.log(`getUserInfo 调用失败`);
					//   },
					// });
					let task = tt.request({
					  url: Api.BASEURI + Api.index.appletLogin_by_toutiao + '/' + res.code,
					  data: {
						  "storeId":Api.STORE_ID
					  },
					  header: {
					    "content-type": "application/x-www-form-urlencoded",
					  },
					  method: "POST",
					  dataType: "JSON", // 指定返回数据的类型为 json
					  success(res) {
						let result = JSON.parse(res.data);
						that.login(result.data);
						that.sessionKey = result.data.sessionKey;
						that.appId = result.data.appId;
						console.log("调用成功", result.data.sessionKey);
						console.log("调用成功", result.data.appId);
						if(result.data.userInfo.phone == ""){
							that.isLogin = true;
						}else{
							uni.switchTab({
								url: '/pages/index/index'
							});
						}
					  },
					  fail(res) {
					    console.log("调用失败", res.errMsg);
					  },
					});
				  },
				  fail(res) {
				    console.log(`login 调用失败`);
				  },
				});
			},
			onGetAuthorize: function(res) {
				my.getOpenUserInfo({
					fail: (res) => {},
					success: (res) => {
						console.log(JSON.parse(res.response).response);
						let userInfo = JSON.parse(res.response).response // 以下方的报文格式解析两层 response
						this.getAuthCode(userInfo);
					}
				});
			},
			wechatH5Login() {
				const that = this
				let href = window.location.origin;
				let page = that.$core.prePage()
			    let fromMemberId = uni.getStorageSync("fromMemberId");
			     console.log(fromMemberId);
				let prePath = "";
				if (undefined != fromMemberId) {
					prePath = '/pages/index/index?memberId=' + fromMemberId
				} else {
					prePath = '/pages/index/index';
				}
				// if (page) {
				// 	prePath = page.__page__.path
				// }
				console.log("前一个页面路径" + prePath);
				window.location = 'https://open.weixin.qq.com/connect/oauth2/authorize?' +
					'appid=' + that.$config.dev.h5Appid + '&redirect_uri=' + escape(href) +
					'&response_type=code&connect_redirect=1&scope=snsapi_userinfo&state=' + escape(prePath) + '#wechat_redirect'
			},
			getAuthCode(aliUserInfo) {
				let that = this;
				//let currentStoreId = uni.getStorageSync("currentStoreId");
				my.getAuthCode({
					scopes: 'auth_base', // 主动授权：auth_user，静默授权：auth_base。或者其它scope
					success: (res) => {
						console.log(res.authCode);
						if (res.authCode) {
							// 认证成功
							// 调用自己的服务端接口，让服务端进行后端的授权认证，并且利用session，需要解决跨域问题
							my.request({
								url: Api.BASEURI + 'applet/loginByAliPay/' + res.authCode, // 该url是您自己的服务地址，实现的功能是服务端拿到authcode去开放平台进行token验证
								data: {
									userInfo: aliUserInfo,
									storeId: Api.STORE_ID
								},
								method: "POST",
								success: (info) => {
									// 授权成功并且服务器端登录成功
									console.log("登录返回信息" + info.data.data);
									that.login(info.data.data);
									let fid = uni.getStorageSync("fromMemberId");
									if (undefined != fid && null != fid) {
										that.fromMemberId = fid;
									}
									let logparams = {
										logs: "绑定会员关系" + info,
										fromMemberId: that.fromMemberId,
									};
									Api.apiCall('get', Api.index.logs, logparams);
									uni.switchTab({
										url: '/pages/index/index'
									});
								},
								fail: (e) => {
									// 根据自己的业务场景来进行错误处理
									console.log(e);
								},
							});
						}
					},
				});
			}
		}
	};
</script>

<style lang="scss">
	page {
		background: #fff;
	}

	.container {
		padding-top: 115px;
		position: relative;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		background: #fff;
	}

	.wrapper {
		position: relative;
		z-index: 90;
		background: #fff;
		padding-bottom: 40upx;
	}

	.back-btn {
		position: absolute;
		left: 40upx;
		z-index: 9999;
		padding-top: var(--status-bar-height);
		top: 40upx;
		font-size: 40upx;
		color: $font-color-dark;
	}
	
	.successtxt {
		font-size: 32rpx;
		font-family: Source Han Sans CN;
		font-weight: 600;
		color: #000000;
		text-align: center;
	}
	
	.tishicontent {
		font-size: 24rpx;
		font-family: Source Han Sans CN;
		font-weight: 400;
		color: #9A9A9A;
		text-indent: 30rpx;
		margin-top: 30rpx;
	}

	.left-top-sign {
		font-size: 120upx;
		color: $page-color-base;
		position: relative;
		left: -16upx;
	}
	
	.buttomafrim {
		width: 200rpx;
		height: 70rpx;
		margin: 0;
		padding: 0;
		text-align: center;
		line-height: 70rpx;
		font-size: 28rpx;
		font-family: Source Han Sans CN;
		font-weight: 400;
		color: #FFFFFF;
		background: #fff;
		border-radius: 100px;
		background: #0DA944;
		color: #fff9f9;
		margin-right: 10rpx;
	}
	
	.unipopup {
		height: 480rpx;
		width: 480rpx;
		background-color: #FFFFFF;
		border-radius: 24rpx;
		padding: 22rpx;
	}

	.right-top-sign {
		position: absolute;
		top: 80upx;
		right: -30upx;
		z-index: 95;

		&:before,
		&:after {
			display: block;
			content: '';
			width: 400upx;
			height: 80upx;
			background: #b4f3e2;
		}

		&:before {
			transform: rotate(50deg);
			border-radius: 0 50px 0 0;
		}

		&:after {
			position: absolute;
			right: -198upx;
			top: 0;
			transform: rotate(-50deg);
			border-radius: 50px 0 0 0;
			/* background: pink; */
		}
	}

	.left-bottom-sign {
		position: absolute;
		left: -270upx;
		bottom: -320upx;
		border: 100upx solid #d0d1fd;
		border-radius: 50%;
		padding: 180upx;
	}

	.welcome {
		position: relative;
		left: 50upx;
		top: -90upx;
		font-size: 46upx;
		color: #555;
		text-shadow: 1px 0px 1px rgba(0, 0, 0, 0.3);
	}

	.input-content {
		padding: 0 60upx;
	}

	.input-item {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		justify-content: center;
		padding: 0 30upx;
		background: $page-color-light;
		height: 120upx;
		border-radius: 4px;
		margin-bottom: 50upx;

		&:last-child {
			margin-bottom: 0;
		}

		.tit {
			height: 50upx;
			line-height: 56upx;
			font-size: $font-sm + 2upx;
			color: $font-color-base;
		}

		input {
			height: 60upx;
			font-size: $font-base + 2upx;
			color: $font-color-dark;
			width: 100%;
		}
	}

	.confirm-btn {
		width: 630upx;
		height: 76upx;
		line-height: 76upx;
		border-radius: 50px;
		margin-top: 70upx;
		/* #ifdef MP-ALIPAY*/
		margin-left: 60upx;
		/* #endif */
		background: linear-gradient(to right, #e68d0f, #e61a0f);
		color: #fff;
		font-size: $font-lg;

		&:after {
			border-radius: 100px;
		}
	}
	
	.buttomopendoor1 {
		width: 200rpx;
		height: 70rpx;
		background: #E3F6E4;
		border: 1px solid #B8E6BA;
		border-radius: 40rpx;
		font-size: 28rpx;
		font-family: Source Han Sans CN;
		font-weight: 400;
		color: #0DA944;
		line-height: 70rpx;
		text-align: center;
		margin-right: 18rpx;
	}

	.forget-section {
		font-size: $font-sm + 2upx;
		color: $font-color-spec;
		text-align: center;
		margin-top: 40upx;
	}

	.register-section {
		position: absolute;
		left: 0;
		bottom: 50upx;
		width: 100%;
		font-size: $font-sm + 2upx;
		color: $font-color-base;
		text-align: center;

		text {
			color: $font-color-spec;
			margin-left: 10upx;
		}
	}
</style>
